#include <grpc/grpc.h>
#include <grpcpp/channel.h>
#include <grpcpp/client_context.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/security/credentials.h>

#include <algorithm>
#include <chrono>
#include <cmath>
#include <iostream>
#include <memory>
#include <string>

#include "data.grpc.pb.h"
#include "data.pb.h"

using std::chrono::system_clock;

using namespace grpc;
using namespace std;

int main(int argc, char** argv) {
  unique_ptr<GrpcService::Stub> stub = GrpcService::NewStub(grpc::CreateChannel(
      "localhost:50051", grpc::InsecureChannelCredentials()));

  {
    ClientContext context;
    InputAction request;
    request.set_option(0);
    DeviceProperty response;

    std::unique_ptr<ClientReader<DeviceProperty> > reader(
        stub->StartReport(&context, request));

    while (reader->Read(&response)) {
      for (int i = 0; i < response.attrinfo_size(); ++i) {
        PropertyInfo info = response.attrinfo(i);
        string key = *info.mutable_attrname();
        if (key == "VehicleInfo") {
          VehicleInfo vi;
          vi.ParseFromString(*info.mutable_attrvalue());
          cout << "VehicleInfo: " << vi.battery() << endl;
        } else if(key == "MotionInfo") {
          MotionInfo mi;
          mi.ParseFromString(*info.mutable_attrvalue());
          cout << "MotionInfo: " << mi.velocity() << endl;
        }
      }
    }
    Status status = reader->Finish();
    if (status.ok()) {
      std::cout << "sayHiStreamly rpc succeeded." << std::endl;
    } else {
      std::cout << "sayHiStreamly rpc failed." << std::endl;
    }
  }

  return 0;
}
